package com.kaochong.xcx.web.handler;


import com.kaochong.xcx.enums.ResultEnum;
import com.kaochong.xcx.exception.AuthorizeException;
import com.kaochong.xcx.exception.KaoChongException;
import com.kaochong.xcx.utils.RequestUtil;
import com.kaochong.xcx.utils.response.ResponseUtils;
import com.kaochong.xcx.utils.response.ResultVO;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

/**
 * 全局异常处理类
 *
 * @author han
 * @date 2018-05-01 16:49
 */
@ControllerAdvice
@Slf4j
public class KaoChongExceptionHandler {
	
	/**
	 * 全局异常处理
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ResultVO handler(HttpServletRequest request, Exception e) {
		String url = RequestUtil.getRequestUrl(request);
		if (e instanceof AuthorizeException) {
			AuthorizeException authorizeException = (AuthorizeException) e;
			log.error("【背单词登录拦截异常】error={}, path={}", e.getMessage(), url);
			return ResponseUtils.error(authorizeException.getCode(), authorizeException.getMessage());
		} else if (e instanceof KaoChongException) {
			KaoChongException kaoChongException = (KaoChongException) e;
			log.error("【背单词异常】error={}, path={}", e, url);
			return ResponseUtils.error(kaoChongException.getCode(), kaoChongException.getMessage());
		} else {
			e.printStackTrace();
			log.error("【其他异常】error={}, path={}", e, url);
			return ResponseUtils.error(ResultEnum.SERVER_ERROR);
		}
	}
}
